
/**
 * Item model/schema 
 */

var counters = require('./counters');
var mongoose = require('mongoose');

var itemSchema =  new mongoose.Schema({
	itemId:String,
	userId:String,
	supplierSKU:String,
	name: String,
	brand:String,
	engine:String,
	brandNumber:String,
	oemNumber:String,
	size:String,
	material:String,
	dimension:String,
	quantity:String,
	price:String,
	description:String,
	made:String,
	make:String,
	car:String,
	year:String,
	cc:String,
	bore:String,
	cylinder:String,
	vmSKU:String,
	createdDate:{type: Date, 'default': Date.now},
	modifiedDate:{type: Date, 'default': Date.now}
});

var item = mongoose.model('Item', itemSchema);

module.exports = function(app) {
	app.get('/items', function(req, res) {
		user.find(function(err, results) {		
			if(err)
				res.send({'Error': err});
			else
				res.send(results);
		});
	});
	
	app.get('/item/:itemId', function(req, res) {
		var itemId = req.params.itemId;
		
		user.findOne({itemId: itemId}, function(err, result) {
			if(err)
				res.send({'Error': err});
			else
				res.send(result);
		});
	});
	
	app.post('/item', function(req, res) {
		var item_ = req.body;
		console.log(item_);
		counters.getNextSequence('item', function(err, itemId) {			
			console.log(counters);
			item_.itemId = itemId;
			//console.log(user_);
			user.findOne({supplierSKU: req.body.supplierSKU}, function(err, result) {
				if(err)
					res.send({'Error': err});
				if(!result) {
					new item(item_).save(function(err, item) {
						if(err)
							res.send({'Error': err});
						else
							res.send(item);
					});
				}
				else
					res.send(500, {'message': 'The user with given username exist', 'error': err});
			});
		});
	});
	
	app.put('/item/:itemId', function(req, res) {
		var item_ = req.body;
		var itemId = req.params.itemId;
		
		item.findOne({itemId: itemId}, function(err, item) {
			if(err)
				res.send({'Error': err});
			else {			
				item.set(item_);			
				item.save(function(error){
					if(error)
						res.send({'Error': err});
					else
						res.send(item);
				});
			}
		});
	});
	
	app.delete('/item/:itemId', function(req, res) {
		var itemId = req.params.itemId;
		
		item.remove({itemId: itemId}, function(err){
			if(err)
				res.send({'Error': err});
			else
				res.send({'Success': 'Successfully deleted the selected item'});
		});
	});
};